package net.sf.rose.task;

import java.util.Date;

import org.apache.log4j.Logger;

import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.service.Service;

/**
 * 类说明：普通后台请求时间太长的功能启动线程去执行
 * 
 * @author fengjian
 * @since 2019/08/27
 */
public abstract class BackTaskThread implements Runnable {

	private static Logger LOG = Logger.getLogger(BackTaskThread.class);

	/**
	 * 启动执行的方法
	 */
	public void start() {
		Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void run() {
		Service service = new Service();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(RoseTaskLogBean.class);
		RoseTaskLogBean log = new RoseTaskLogBean();
		// 记录开始任务
		try {
			log.setTaskType(RoseTaskLogBean.TASK_TYPE_USER);
			log.setStartTime(new Date());
			log.setTaskInformation(getInformation());
			query.createSaveSql(log);
			dao.update();
			service.commit();
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			return;
		}
		String result = "成功";
		String message = null;
		// 执行任务
		try {
			message = excute(service);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result = "失败";
			message = e.getMessage();
			service.rollback();
		}
		// 记录结束任务
		try {
			service.setCurrentDatabaseName(Service.getDefaultDatabaseName());
			log.setEndTime(new Date());
			log.setResult(result);
			log.setMessage(message);
			query.createUpdateSql(log);
			dao.update();
			service.commit();
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		} finally {
			service.close();
		}
	}

	/**
	 * 执行线程业务
	 * @param service 数据库连接
	 * @return 执行结果
	 * @throws Exception 执行异常
	 */
	public abstract String excute(Service service) throws Exception;

	/**
	 * 获取任务说明信息
	 * @return 任务说明
	 */
	public abstract String getInformation();

}
